from django.shortcuts import render
from django.http import JsonResponse
from django.views.generic import ListView
from django.views.decorators.http import require_POST
from utils.paginationbase import PaginationBase
from .models import Book


class BookListView(ListView, PaginationBase):
    model = Book
    template_name = 'book_list.html'
    context_object_name = 'books'
    paginate_by = 10
    ordering = '-c_time'
    page_kwarg = 'p'

    def get_context_data(self, **kwargs):
        context = super(BookListView, self).get_context_data(**kwargs)
        # context['username'] = 'zhiliao'
        paginator = context.get('paginator')
        page_obj = context.get('page_obj')
        pagination_data = self.get_pagination_data(paginator, page_obj, 3, self.model)
        context.update(pagination_data)
        return context


def to_add_book(request):
    return render(request, 'book_add.html')


@require_POST
def add_book(request):
    name = request.POST.get('name')
    content = request.POST.get('content')
    book = Book(name=name, content=content)
    book.save()

    return JsonResponse({'code': 200, 'msg': 'success'})
